<?php
/**
 * @apiVersion 1.0.0
 * @api {POST} /wechat/User/getUserInfo 004获取用户信息接口OK
 * @apiDescription 获取用户信息接口
 * @apiGroup Pub
 * @apiPermission 公众号

 * @apiSuccess  {Int} code 状态
 * @apiSuccess  {Object} data 元数据
 * @apiSuccess  {String} msg 错误说明
 * @apiSuccessExample {json} 响应示例:
{
    "code": 1,
    "msg": "登录成功",
    "data": {
        "userID": 237,  //用户id
        "photo": null,  //头像
        "mobile": "15573179664",  //手机号
        "nickname": null,  //昵称
        "sex": 0,  //性别：
        "trueName": "张三",  //真实姓名
        "card": "273273723723",  //身份证号码
        "updataTime": 1620157828,
        "addTime": 1620157741,  //注册时间
        "status": 1,      //状态： 1正常 0禁用
        "serialNumber": null,
        "appType": null,
        "mobileType": null,
        "password": null,
        "payPassword": null,
        "agent": null,
        "clientIP": "3740760482",
        "location": null,
        "judge": 0,
        "version": null,
        "latitude": null,
        "longitude": null,
        "apliayUsername": null, //支付宝账号
        "apliayPassword": null, //支付宝密码
        "apliayPayPassword": null,  //支付宝支付密码
        "wechatUsername": null, //微信账号
        "wechatPassword": null, //微信密码
        "wechatPayPassword": null,  //微信支付密码
        "depositUsername": null,    //提现账号
        "depositType": null,    //提现类型： 1支付宝 2微信
        "platformID": 0,    //平台id
        "statusCheck": -1,
        "xrkCode": null,    //葵码
        "checkTime": null,
        "checkManger": null,
        "cMobile": "",
        "depositRealname": "",
        "openID": null, //微信openid
        "unionID": null,    //开发平台id
        "loginTimes": 3,
        "lastLoginTime": 1620157828
    }
}

 * //操作未成功提示信息
 * {
 *      "code":0,
 *      "msg" :"错误说明"
 * }
 */


/**
 * @apiVersion 1.0.0
 * @api {POST} /wechat/Signin/getSignData 4001获取签到数据OK
 * @apiDescription 获取签到数据
 * @apiGroup Sign
 * @apiPermission 公众号
 * @apiParam {date} time 时间
 * @apiParamExample {json} 请求示例:
 * {
 *      "time": '2021-05-19',
 * }

 * @apiSuccess  {Int} code 状态
 * @apiSuccess  {Object} data 元数据
 * @apiSuccess  {String} msg 错误说明
 * @apiSuccessExample {json} 响应示例:
{
    "code": 1,
    "msg": "操作成功",
    "data": {
        "daysMoney": 15,   //每日奖励金额
        "status": 1,   //签到状态 1已签到 2未签到
        "task_list": [ //任务列表
            {
                "taskID": 1,
                "title": "一秒助力",    //任务名称
                "logo": "1.png",    //图片
                "rewardMoney": "0.05",  //奖励金额
                "completeText": "已完成"   //完成状态
            }
        ]
    }
}

 * //操作未成功提示信息
 * {
 *      "code":0,
 *      "msg" :"错误说明"
 * }
 */

/**
 * @apiVersion 1.0.0
 * @api {POST} /wechat/Signin/signAdd 4002签到ok
 * @apiDescription 签到
 * @apiGroup Sign
 * @apiPermission 公众号

 * @apiSuccess  {Int} code 状态
 * @apiSuccess  {Object} data 元数据
 * @apiSuccess  {String} msg 错误说明
 * @apiSuccessExample {json} 响应示例:
{

}

 * //操作未成功提示信息
 * {
 *      "code":0,
 *      "msg" :"错误说明"
 * }
 */

namespace app\wechat\controller;


use app\model\FreshAdminAuthGroupAccess;
use app\model\FreshAdminUser;

use app\model\FreshAdminUserData;
use app\model\UserAward;
use app\util\ReturnCode;
use app\util\Tools;
use think\Db;
use think\Exception;

class Signin extends Base {


    /**
     * 获取签到数据
     */
    public function getSignData11() {

        $param = $this->request->post();
        if(!isset($param['time'])) return $this->buildFailed(-1, '时间参数不能为空');
        $user_allot = Db::name('user_allot')
            ->where(['userID' => $this->userInfo['userID']])
            ->order('id desc')
            ->find();
        if(isset($user_allot['id'])){
            if($user_allot['status'] == 1){
                $task = Db::name('task_record')->alias('a')
                    ->field("b.taskID,b.title, b.rewardMoney,b.logo")
                    ->join('task b', 'a.taskID=b.taskID', 'LEFT')
                    ->where(['a.status' => 1, 'opMid' => $user_allot['opMid']])
                    ->select();
                foreach ($task as &$item){
                    $item['completeText'] = '已完成';
                    $item['rewardMoney'] = Tools::bcCalculate($item['rewardMoney'], 100, '/');
                }
                $award = Db::name('user_award')->where(['userID' => $this->userInfo['userID'],'addDate' => $param['time']])
                    ->find();
                if(isset($award['id'])){
                    if($award['status'] == 1){
                        $status = 1;
                    }else{
                        $status = 2;
                    }
                }else{
                    $status = 2;
                }
                return $this->buildSuccess(['daysMoney' => 15, 'task_list' => $task, 'status' => $status], '操作成功');
            }
            if($user_allot['status'] == 2){
                $task = Db::name('task_record')->alias('a')
                    ->field("b.taskID,b.title, b.rewardMoney,b.logo")
                    ->join('task b', 'a.taskID=b.taskID', 'LEFT')
                    ->where(['a.status' => 1, 'opMid' => $user_allot['opMid']])
                    ->select();
                foreach ($task as &$item){
                    $item['completeText'] = '未完成';
                    $item['rewardMoney'] = Tools::bcCalculate($item['rewardMoney'], 100, '/');
                }
                return $this->buildSuccess(['daysMoney' => 15, 'task_list' => $task, 'status' => 2], '操作成功');
            }

            if($user_allot['status'] == 3){
                return $this->buildFailed(-1, '账号未分配');
            }
            return $this->buildFailed(-1, '账号状态异常');
        }else{
            return $this->buildFailed(-1, '未绑定操作员');
        }

    }

    public function getSignData() {

        $param = $this->request->post();
        if (!isset($param['time'])) return $this->buildFailed(-1, '时间参数不能为空');

        $award = Db::name('user_award')->where(['userID' => $this->userInfo['userID'], 'addDate' => date('Ymd', strtotime($param['time']))])
            ->find();
        if (isset($award['id'])) {
            if ($award['status'] == 1) {
                $status = 1;
            } else {
                $status = 2;
            }
            $user_allot = Db::name('user_allot')
                ->where(['userID' => $this->userInfo['userID']])
                ->order('id desc')
                ->find();
            if(isset($user_allot['id'])){
                $task = Db::name('task_record')->alias('a')
                    ->field("b.taskID,b.title, b.rewardMoney,b.logo")
                    ->join('task b', 'a.taskID=b.taskID', 'LEFT')
                    ->where(['a.status' => 1, 'opMid' => $user_allot['opMid']])
                    ->select();
                foreach ($task as &$item){
                    $item['completeText'] = '已完成';
                    $item['rewardMoney'] = Tools::bcCalculate($item['rewardMoney'], 100, '/');
                }
            }else{
                $task = [];
            }
            return $this->buildSuccess(['daysMoney' => 15, 'task_list' => $task, 'status' => $status], '操作成功');
        } else {
            return $this->buildFailed(-1, '签到异常');
        }



    }

    public function signAdd(){
        $domain = $_SERVER['HTTP_HOST'];
        $config = config('program.'.$domain);
//        var_dump($config['AppID']);exit();
        $userID = $this->userInfo['userID'];
        Db::startTrans();
        try{
            $user = Db::name('user')->where('userID', $userID)->find();
            if($user['isAllot'] != 1) throw new Exception('用户状态异常，请联系操作员解决');

            $user_award = UserAward::get(['userID'=> $userID,  'addDate' => date('Ymd')]);
            if(!isset($user_award->id))      throw new Exception('签到异常[-1]');
            if($user_award->status == 1)    throw new Exception('当日已签到');
            $amount = $user_award->money;
            $userData = \app\model\User::get(['userID' => $userID]);
//            var_dump(1111);exit();
            $flag = Db::name('user')->where(['userID' => $userID])
                ->update(['money' => Tools::bcCalculate($userData['money'], $amount, '+') * 100]);
            if(!$flag) throw new Exception('签到失败');

            $logModel = new \app\model\UserMoneyLog();

            $flag = $logModel->create([
                'userID' => $userID,
                'amount' => $amount,
                'balance' => Tools::bcCalculate($userData['money'], $amount, '+'),
                'ordertype' => 1,
                'turnover' => 1,
                'content' => date('Ymd').'用户签到奖励'.$amount.'元',
                'relateID' => 0,
            ]);
            if(!$flag) throw new Exception('插入日志流水失败');

            $flag = Db::name('user_award')->where(['id' => $user_award->id])
                ->update(['status' => 1,'payDate' => date('Ymd'), 'updateTime' => time()]);
            if(!$flag)  throw new Exception('更新提现记录失败!');

            Db::commit();
            return $this->buildSuccess([]);
        }catch(\Exception $e){
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, $e->getMessage());
        }
    }


}
